/*jslint sloppy: true */
/*global probe, angular */
probe.controller('Main', function ($scope, $element, ocDialog,
									scriptEngine, GET_FRAME, project) {

	var DI = $scope.DI = ocDialog.queryDI($element),
		$area = angular.element('<div class="trigger area"></div>');

	// from editor controller.
	$scope.getCaseOptions = angular.noop;
	$scope.caseInstance = null;
	function buildCaseInstance() {
		$scope.getCaseOptions(function ($case, dictionary) {
			scriptEngine.getCase($case.code, dictionary)(function (err, $CI) {
				// (C)ase (I)nstance.
				if (err) {
					throw err;
				}
				$scope.caseInstance = $CI;
			});
		});
	}

	function playerExceptionHandle(fn, actionName) {
		try {
			fn();
		} catch (error) {
			ocDialog.alert({
				title: actionName + '失败',
				message: '原因：\n' + error
			}, DI);
			$scope.playerStatus = 'idle';
		}
	}

	function showStatus() {
		var ci = $scope.caseInstance;
		$scope.$apply(function () {
			$scope.status = '引擎 - ' +
				ci.$$state + ' 第' + (ci.$$currentLoop + 1) + '循环';
		});
	}

	$scope.homeUrl = project.probeOrigin;

	scriptEngine.setup({
		successCallback: function successCallback() {
			ocDialog.getNewDI('upload', this).then(function (newDI) {
				newDI.openDialogFrom(DI);
			});
			$scope.mask = false;
			$scope.caseInstance = null;
			$scope.player.status = 'idle';
		},
		runCallback: function runCallback(currentIns) {
			($scope.emphasizeInstruction || angular.noop)(currentIns);
			showStatus();
		},
		triggerCallback: function triggerCallback(objectDOM) {
			if (!$scope.highlightIns) {
				return;//user disabled highlight
			}

			var frameOffset = GET_FRAME().getBoundingClientRect(),
				offset = objectDOM.getBoundingClientRect();

			$area.css({
				top: (offset.top + frameOffset.top - 2) + 'px',
				left: (offset.left + frameOffset.left - 2) + 'px',
				width: offset.width + 'px',
				height: offset.height + 'px',
				'background-color': 'rgba(96, 209, 251, 0.9)'
			});

			angular.element(document.body).append($area);

			setTimeout(function () {
				$area.css({'background-color': 'transparent'});
			}, 500);

			setTimeout(function () {
				$area.remove();
			}, 1500);
		}
		//runExceptionHandle: null,//lemoncase use console.error
	});

	$scope.p = $scope.player = {
		status: 'idle'
	};
	$scope.buildAndPlay = function () {
		//TODO ocDialog issue#30
		scriptEngine.setup({
			contextFrame: GET_FRAME()
		});
		playerExceptionHandle(function () {
			buildCaseInstance();
			$scope.caseInstance.start();
			$scope.player.status = 'run';
			$scope.mask = true;
		}, '构建与启动');
	};
	$scope.pause = function () {
		playerExceptionHandle(function () {
			$scope.caseInstance.suspend();
			$scope.player.status = 'wait';
		}, '暂停测试');
	};
	$scope.stop = function () {
		playerExceptionHandle(function () {
			$scope.caseInstance.stop();
			$scope.player.status = 'idle';
			$scope.mask = false;
		}, '停止测试');
	};
	$scope.resume = function () {
		playerExceptionHandle(function () {
			$scope.caseInstance.resume();
			$scope.player.status = 'run';
		}, '继续测试');
	};
	$scope.highlightIns = true;

	// 控制边栏的固定与显隐
	$scope.iframeGrid = {
		right: '20rem'
	};
	$scope.isInactive = false;
	$scope.isFixed = true;
	$scope.togglePanel = function () {
		$scope.isInactive = !$scope.isInactive;
		$scope.isFixed = $scope.isInactive;
		$scope.fixedPanel();
	};
	$scope.fixedPanel = function () {
		$scope.isFixed = !$scope.isFixed;
		$scope.iframeGrid.right = $scope.isFixed ? '20rem' : 0;
	};

	// Iframe的大小控制
	$scope.iframeSize = {
		width: '100%',
		height: '100%'
	};
	$scope.fullScreen = function () {
		$scope.isProjectFull = true;
		$scope.iframeSize.width = '100%';
		$scope.iframeSize.height = '100%';
	};
	$scope.project = {
		width: function (newWidth) {
			var size = $scope.iframeSize;
			if (angular.isDefined(newWidth)) {
				size.width = newWidth.match(/\d+/)[0] + 'px';
			}
			return size.width;
		},
		height: function (newHeight) {
			var size = $scope.iframeSize;
			if (angular.isDefined(newHeight)) {
				size.height = newHeight.match(/\d+/)[0] + 'px';
			}
			return size.height;
		}
	};
	$scope.isProjectFull = true;
	$scope.history = window.history;

	//遮罩
	$scope.mask = false;
	
	// init
	DI.$$scope.buttons = [
		{
			className: 'simulation'
		},
		{
			className: 'api'
		},
		{
			className: 'regression'
		},
		{
			className: 'monkey'
		},
		{
			className: 'availability'
		},
		{
			className: 'taskmode'
		}
	];
	$scope.menu = [
		{
			title: '文件(F)',
			menu: [
				{
					title: '新建(N)',
					attr: 'ng-click="newCase()"'
				},
				{
					title: '打开(O)',
					attr: 'ng-click="openCase()"'
				},
				null,
				{
					title: '保存(S)',
					attr: 'ng-click="saveCase()"'
				},
				{
					title: '另存为',
					attr: 'ng-click="saveAsCase()"'
				},
				null,
				{
					title: '关闭探针(X)',
					attr: 'oc-dialog-close'
				}
			]
		},
		{
			title: '编辑(E)',
			menu: [
				{
					title: '撤销',
					attr: 'ng-click="undo()" ng-disabled="simple"'
				},
				{
					title: '重复',
					attr: 'ng-click="redo()" ng-disabled="simple"'
				},
				null,
				{
					title: '删除',
					attr: 'ng-click="deleteIns()"'
				},
				{
					title: '全部删除',
					attr: 'oc-alert-open="trashCase"'
				}
			]
		},
		{
			title: '视图(V)',
			menu: [
				{
					title: '平铺工作区',
					attr: 'ng-click="isProjectFull=true"'
				},
				null,
				{
					title: '显示用例编辑栏',
					attr: 'ng-click="isInactive=false" ng-show="isInactive"'
				},
				{
					title: '隐藏用例编辑栏',
					attr: 'ng-click="isInactive=true" ng-hide="isInactive"'
				}
			]
		},
		{
			title: '对象(E)',
			menu: [
				{
					title: '字典管理器',
					attr: 'oc-dialog-open="{name:\'dictionary/management\'}"'
				},
				{
					title: '子过程',
					attr: 'disabled'
				},
				{
					title: '元件库',
					attr: 'oc-dialog-open="{name:\'object/editor\'}"'
				},
				{
					title: '压力测试',
					attr: 'oc-dialog-open="{name:\'loadTest\'}"'
				}
			]
		},
		{
			title: '帮助(H)',
			menu: [
				{
					title: '探针文档',
                    attr:  'oc-dialog-open="{name:\'help/probeDoc\'}"'
				},
				{
					title: '测试管理服务',
                    attr:  'oc-dialog-open="{name:\'help/testManagementService\'}"'
				},
				{
					title: 'LemonCase语言',
                    attr:  'oc-dialog-open="{name:\'help/lemonCase\'}"'
				},
				null,
				{
					title: '关于LemonceProbe',
					attr: 'oc-dialog-open="{name:\'help/about\'}"'
				}
			]
		}
	];
});
